import datetime
import time
class LimitTool:
    def readCode(self,randomCode):
        #传进来的是13位字符串，只要中间的，然后进行-1.判断是否离上次的时间过近
        tempCode = randomCode.replace('0','')
        if tempCode != "":
            randomCode = int(randomCode) - 1
            randomCode = str(randomCode)
        # code = code.zfill(13)
            return randomCode
        else:
            return None
    def __init__(self, delay):
        self.delay = delay
        self.codes = {}

    def wait(self, randomCode):
        print('randomcode is ' + randomCode)
        last_accessed = self.codes.get(self.readCode(randomCode))#get函数在domain不存在时返回None
        print('last_accessed is ')
        print(last_accessed)
        print('wait function')
        print(self.delay > 0)
        print( last_accessed is not None)
        if self.delay > 0 and last_accessed is not None:
            sleep_secs = self.delay - (datetime.datetime.now() - last_accessed).seconds
            if sleep_secs > 0:
                print('need to sleep')
                time.sleep(sleep_secs)
        else:
            print('no need to sleep')
        print(self.codes)
        self.codes[randomCode] = datetime.datetime.now()
        print(self.codes.__len__())


limitToolSingleton = LimitTool(3)
